export{}
//生成指定范围随机数
const randomNum = (min: number, max:number) => Math.floor(Math.random() * (max - min + 1)) + min;

//数组乱序
const arrScrambling = (arr:number[]) => {
    for (let i = 0; i < arr.length; i++) {
      const randomIndex = Math.round(Math.random() * (arr.length - 1 - i)) + i;
      [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
    }
    return arr;
}

//数组扁平化
const flatten = (arr: any[]): any[] => {
  let result: any[] = [];
  for (let i = 0; i < arr.length; i++) {
      if (Array.isArray(arr[i])) {
          result = result.concat(flatten(arr[i]));
      } else {
          result.push(arr[i]);
      }
  }
  return result;
}

// 数组中获取随机数
const sample = (arr:number[])=>{
  return arr[Math.floor(Math.random() * arr.length)]
}

// 生成随机字符串
const randomString = (len:number)=>{
  let str = '';
  for(let i = 0; i < len; i++){
    str += String.fromCharCode(Math.floor(Math.random() * 26) + 97);
  }
  return str;
}
//字符串首字母大写
const fistLetterToUpper = (str:string)=>{
  return str.charAt(0).toUpperCase() + str.slice(1);
}

//手机号中间四位变成*
const telFormat = (tel:string) => {
  tel = String(tel); 
  return tel.substr(0,3) + "****" + tel.substr(7);
};

//驼峰命名转换成短横线命名
const getKebabCase = (str:string) => {
  return str.replace(/[A-Z]/g, (item) => '-' + item.toLowerCase())
}

//短横线命名转换成驼峰命名
const getCamelCase = (str:string) => {
  return str.replace( /-([a-z])/g, (i, item) => item.toUpperCase())
}

//数字转化为大写金额
export const digitUppercase = (n: number) => {
  
  const fraction = ['角', '分'];
  const digit = [
      '零', '壹', '贰', '叁', '肆',
      '伍', '陆', '柒', '捌', '玖'
  ];
  const unit = [
      ['元', '万', '亿'],
      ['', '拾', '佰', '仟']
  ];
  n = Math.abs(n);
  let s = '';
  for (let i = 0; i < fraction.length; i++) {
      s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
  }
  s = s || '整';
  n = Math.floor(n);
  for (let i = 0; i < unit[0].length && n > 0; i++) {
      let p = '';
      for (let j = 0; j < unit[1].length && n > 0; j++) {
          p = digit[n % 10] + unit[1][j] + p;
          n = Math.floor(n / 10);
      }
      s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
  }
  return s.replace(/(零.)*零元/, '元')
      .replace(/(零.)+/g, '零')
      .replace(/^整$/, '零元整');
};

//存储loalStorage
 const loalStorageSet = (key: string, value:string) => {
  if (!key) return;
  if (typeof value !== 'string') {
      value = JSON.stringify(value);
  }
  window.localStorage.setItem(key, value);
};

//获取localStorage
const loalStorageGet = (key: string) => {
  if (!key) return;
  return window.localStorage.getItem(key);
};

//删除localStorage
 const loalStorageRemove = (key: string) => {
  if (!key) return;
  window.localStorage.removeItem(key);
};

// 设置cookie
const setCookie = (key: string, value:string, expire:number) => {
  const d = new Date();
  d.setDate(d.getDate() + expire);
  document.cookie = `${key}=${value};expires=${d.toUTCString()}`
};

//读取cookie
const getCookie = (key: string) => {
  
  const cookieStr = unescape(document.cookie);
     const arr = cookieStr.split('; ');
     let cookieValue = '';
     for (let i = 0; i < arr.length; i++) {
         const temp = arr[i].split('=');
         if (temp[0] === key) {
             cookieValue = temp[1];
             break
     }
  }
  return cookieValue
};

//正则校验身份证号码
export const checkCardNo = (value: string) => {
  let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return reg.test(value);
};
//正则校验是否包含中文
export const haveCNChars = (value:string) => {
  
    return /[\u4e00-\u9fa5]/.test(value);
}

//获取URL参数列表
interface GetRequest {
  (url: string): { [key: string]: string | string[] | number | boolean };
}

const GetRequest: GetRequest = (url: string): { [key: string]: string | string[] | number | boolean } => {
  const paramsStr: string | null = url.substring(url.indexOf('?') + 1);
  if (!paramsStr) {
      return {};
  }
  const paramsArr: string[] = paramsStr.split('&');
  let paramsObj: { [key: string]: string | string[] | number | boolean } = {};

  paramsArr.forEach((param: string) => {
      const [key, value] = param.split('=');
      if (value !== undefined) {
          let val: string | number = decodeURIComponent(value);
          // 如果值是数字，则转换为数字类型
          if (/^\d+(\.\d+)?$/.test(val)) {
              val = parseFloat(val);
          }
          // 如果键已存在，并且是数组，则添加到数组中
          if (paramsObj.hasOwnProperty(key) && Array.isArray(paramsObj[key])) {
              (paramsObj[key] as string[]).push(val as string);
          } else if (paramsObj.hasOwnProperty(key)) { // 如果键已存在，但不是数组，则创建数组
              paramsObj[key] = [paramsObj[key] as string, val as string];
          } else { // 如果键不存在，则直接添加
              paramsObj[key] = val;
          }
      } else { // 如果没有值，则默认为 true
          paramsObj[key] = true;
      }
  });

  return paramsObj;
};

//键值对拼接成URL参数
export const params2Url = (obj: { [key: string]: string }): string => {
  let params = [];
  for (let key in obj) {
      params.push(`${key}=${obj[key]}`);
  }
  return encodeURIComponent(params.join('&'));
}

//判断是移动还是PC设备
const isMobile = ():('mobile'|'desktop') => {
  if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
        return 'mobile';
  }
  return 'desktop';
}

//判断是Windows还是Mac系统
const osType = ():('windows'|'mac') => {
  const agent = navigator.userAgent.toLowerCase();
  const isMac = /macintosh|mac os x/i.test(navigator.userAgent);
  const isWindows = agent.indexOf("win64") >= 0 || agent.indexOf("wow64") >= 0 || agent.indexOf("win32") >= 0 || agent.indexOf("wow32") >= 0;
  if (isWindows) {
      return "windows";
  }
  if(isMac){
      return "mac";
  }
  throw new Error("Unable to determine OS type");
}

//滚动到页面顶部
const height:number = document.documentElement.scrollTop || document.body.scrollTop;
const scrollToTop = (height:number) => {
    if (height > 0) {
      window.requestAnimationFrame(scrollToTop);
      window.scrollTo(0, height - height / 8);
    }
  }
 
//获取可视窗口高度
const getClientHeight = (): number => {
  let clientHeight: number = 0;
  if (document.body.clientHeight && document.documentElement.clientHeight) {
      clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
  } else {
      clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
  }
  return clientHeight;
}

//格式化时间
const dateFormater = (formater: string, time?: string | number | Date): string => {
  let date = time ? new Date(time) : new Date(),
      Y = date.getFullYear() + '',
      M = date.getMonth() + 1,
      D = date.getDate(),
      H = date.getHours(),
      m = date.getMinutes(),
      s = date.getSeconds();
  return formater.replace(/YYYY|yyyy/g, Y)
      .replace(/YY|yy/g, Y.substr(2, 2))
      .replace(/MM/g, (M < 10 ? '0' : '') + M)
      .replace(/DD/g, (D < 10 ? '0' : '') + D)
      .replace(/HH|hh/g, (H < 10 ? '0' : '') + H)
      .replace(/mm/g, (m < 10 ? '0' : '') + m)
      .replace(/ss/g, (s < 10 ? '0' : '') + s);
}
//防抖函数
const debounce = (func: Function, wait: number): Function => {
  let timeout: any = null;
  return function (this: unknown, ...args: any[]): void {
      if (timeout !== null) clearTimeout(timeout);
      timeout = setTimeout(() => {
          func.apply(this, args);
      }, wait);
  };
};

//节流函数
const throttle = (func: Function, wait: number): Function => {
  let timeout: any = null;
  let called = false;
  return function (this: unknown, ...args: any[]): void {
      if (!called || !timeout) {
          if (timeout !== null) clearTimeout(timeout);
          timeout = setTimeout(() => {
              timeout = null;
              called = false;
          }, wait);
          func.apply(this, args);
          called = true;
      }
  };
};
//对象深拷贝
const deepClone = (obj: any): any => {
  if (obj === null || typeof obj !== 'object') {
      return obj;
  }
  if (obj instanceof Date) {
      return new Date(obj.getTime());
  }
  if (obj instanceof Array) {
      let arr: any[] = [];
      for (let i = 0; i < obj.length; i++) {
          arr[i] = deepClone(obj[i]);
      }
      return arr;
  }
  if (obj instanceof Object) {
      let o: any = {};
      for (let key in obj) {
          if (obj.hasOwnProperty(key)) {
              o[key] = deepClone(obj[key]);
          }
      }
  }
}
